<template>
  <div class="common-layout">
    <el-form  class="header" :model="queryParam" ref="queryRef" :inline="true">
      <el-form-item label="组号" prop="group">
        <el-input clearable v-model="groupNum"
                  style="width: 200px;"
                  @blur="inputKeyUpEvent"
                  placeholder="请输入组号(1-18)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchByUnit">查询</el-button>
        <el-button @click="resetQuery">重新排列</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
            type="danger"
            plain
            :disabled="multiple"
            @click="hiddenEng"
        >{{ multipleEng ? '隐藏英文' : '显示英文' }}
        </el-button>
        <el-button
            type="warning"
            plain
            :disabled="multiple"
            @click="hiddenChn"
        >{{ multipleChn ? '隐藏中文' : '显示中文' }}
        </el-button>

        <el-button
            type="success"
            @click="submitRecordStudy"
        >
          提交记录
        </el-button>
      </el-form-item>
      <el-form-item style="margin-left: auto;">

        <div style="display: inline-flex" class="time-display">{{ formattedTime }}</div>

        <el-button
            plain type="primary" @click="startTimer"
            :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)">
          {{
            isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始倒计时' : (isRunning ? '运行中' : '启动')
          }}
        </el-button>

        <el-button plain type="warning" :disabled="!isRunning" @click="pauseTimer">暂停</el-button>

        <el-button plain :disabled="isRunning" @click="resetTimer">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="20">
      <el-col :sm="24" :lg="24" style="padding-left: 20px;padding-right: 20px">
        <el-table
            v-loading="loading"
            :data="pageData"
            row-key="_id"
            :expand-row-keys="expandRowKeys"
            @expand-change="handleExpandChange"
            :default-sort="{ prop: 'seed', order: 'descending' }"
            @selection-change="handleSelectionChange"
            border
            stripe
            highlight-current-row
        >
          <el-table-column type="selection" width="40" align="center"/>
          <el-table-column v-if="false" type="index" :index="indexMethod"/>
          <el-table-column label="编号" v-if="false" width="210" prop="_id"/>
          <el-table-column label="单词/词组" width="180" align="center" prop="name"/>
          <el-table-column label="词性以及释义" align="center" prop="chinese"/>
          <el-table-column label="操作" align="center" width="350" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link @click="handleColumnAudio(scope.row)" type="success">发音</el-button>
              <el-button link @click="rowClick(scope.row)" type="primary">已学</el-button>
              <el-button link type="danger" @click="hiddenColumn1(scope.row)">
                {{ scope.row.statusEng ? '显示英文' : '隐藏英文' }}
              </el-button>
              <el-button link type="warning" @click="hiddenColumn2(scope.row)">
                {{ scope.row.statusChn ? '显示中文' : '隐藏中文' }}
              </el-button>
              <el-button link @click="getNetworkInfo(scope.row)" style="color: #421f7d">具体释义</el-button>
            </template>
          </el-table-column>
          <!-- 展开图标列 -->
          <el-table-column type="expand">
            <template #default="props">
              <div v-if="props.row.loadMore" v-html="props.row.loadMoreHtml" class="wordSentence"></div>
              <div style="float: right;color: red;margin-right: 20px" v-else>
                点击‘具体释义’后加载例句
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :sm="24" :lg="8" style="padding-left: 50px">
      </el-col>
    </el-row>

    <el-backtop class="custom-backtop" :bottom="100">
      <div
          style="
        height: 100%;
        width: 100%;
        background-color: var(--el-bg-color-overlay);
        box-shadow: var(--el-box-shadow-lighter);
        text-align: center;
        line-height: 40px;
        color: #1989fa;
      "
      >
        {{ correctNum }} / {{ total }}
      </div>
    </el-backtop>
  </div>
</template>

<script setup>
// 查询
import {
  getWordInfoMore,
  getWordSentence,
  getMessageBoxContent
} from "@/api/word/index.js";
import {addStudy_record, getUsedTime} from "@/api/word/wordRecord.js";
import {ref} from "vue";
import {useTimerStore} from '@/store/timer';
import {ElMessageBox} from "element-plus";
import {isNumberStr} from "@/utils/index.js";
import {getGroupData,putStudyData} from "@/api/senior/index.js";
import {shuffleArray} from "@/api/utils/index.js";

const timerStore = useTimerStore();
// 从 store 中解构 actions
const {startTimer, pauseTimer, resetTimer, toggleMode, setInitialTime} = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const {formattedTime, isRunning, isCountdown, initialTime, currentTime} = storeToRefs(timerStore); // 添加 currentTime

let recordFrom = ref({})
let testStartTime = ref(null)
let testEndTime = ref(null)
let testStartTimeStatus = ref(true)
let groupNum = ref(Math.ceil(Math.random() * 18))
let queryParam = ref({})

const {proxy} = getCurrentInstance()

let pageData = ref([])
let correctNum = ref(0)
let studyRecord = ref([])
let selectedData = ref([])
let selectedDataTemp = ref([])
let practiceId = ref(null)
let total = ref(0)
let rowRecordMap = ref(new Map)
let loading = false
let multiple = ref(true)
let multipleEng = ref(true)
let multipleChn = ref(true)

// 允许多个 key
const expandRowKeys = ref([])

// 正确处理：添加或移除 key，而不是覆盖
const handleExpandChange = (row, expandedRows) => {
  // expandedRows 是当前所有展开的行数组
  // console.log('当前展开的行：', expandedRows.map(r => r._id))
  // 如果你想同步 expandRowKeys，可以这样：
  expandRowKeys.value = expandedRows.map(r => r._id)
}

initPage()

//已学，移除本行
function rowClick(row) {
  let number = pageData.value.indexOf(row);
  pageData.value.splice(number, 1);
  proxy.$modal.msgWarning("学会了")
  startTimer()
  let temp = row
  delete temp['_id']
  delete temp['seed']
  temp['practiceId'] = practiceId.value
  temp['orderTime'] = formattedTime.value
  temp['type'] = 'table'  //学习类型-列表/卡片
  putStudyData(temp) //提交记录-单个-静默

  //学习个数
  correctNum.value++

  //记录首次点击的时间
  if (testStartTimeStatus.value) {
    testStartTime.value = Date.now()
    startTimer()
    testStartTimeStatus.value = false
  }

  studyRecord.value.push(temp)
}

function inputKeyUpEvent() {
  if (groupNum.value === '') {
    return
  }
  if (!isNumberStr(groupNum.value) || groupNum.value % 1 !== 0) {
    proxy.$modal.msgWarning("组号必须为整数")
    return
  }
  if (groupNum.value > 18 || groupNum.value < 1) {
    proxy.$modal.msgWarning("组号必须在1-18之间")
    return
  }
  queryParam.value.group = groupNum.value
}

function getNetworkInfo(row) {
  let word = row.name
  // console.log(word)
  if (word === null || word === undefined) {
    return
  }
  if (word.toString().indexOf("/") > -1) {
    proxy.$modal.msgWarning("不支持短语查询")
    return
  }
  row.loadMore = true
  getWordInfoMore(word).then(res => {
    if (res.code === 200) {
      row.wordMore = res.data
      // console.log(res.data)
      let wordInfoMore = getMessageBoxContent(res.data);
      row.loadMoreHtml = getWordSentence(res.data.sentences);
      ElMessageBox.alert(wordInfoMore, word, {
        confirmButtonText: 'OK',
        dangerouslyUseHTMLString: true,
        customStyle: {
          'width': '1200px',
        },
      })
    } else {
      proxy.$modal.msgWarning("请求失败")
    }
  });
}

function handleQuery() {
  // console.log(groupNum.value)
  const group = {group : groupNum.value}
  getGroupData(group).then((res) => {
    let index = 0
    if (res.code === 200) {
      // console.log(res)
      pageData.value = shuffleArray(res.data)
      total.value = res.data.length
      pageData.value.forEach(item => {
        item.loadMore = false
        item.voiceCount = 0
        item.loadMoreHtml = ''
        item.wordMore = {}
        item.statusEng = false
        item.statusChn = false
        item.index = index++
      })
    }
  })
  rowRecordMap.value.clear()
}

function initPage() {
  handleQuery()
  practiceId.value = Math.random().toString().substring(2)
}

function submitRecordStudy() {
  if (correctNum.value === 0) {
    proxy.$modal.msgWarning("学习的记录为空")
    return
  }
  if (pageData.value.length > 0) {
    proxy.$modal.msgWarning("还有未学习的单词")
  }

  proxy.$modal.confirm('是否确认提交').then(function () {
    testEndTime.value = Date.now()
    pauseTimer() //完成学习时，停止计时器

    recordFrom.value.wordNum = total.value
    recordFrom.value.practice = practiceId.value
    recordFrom.value.complete = groupNum.value

    // console.log(recordFrom.value)
    recordFrom.value.usedTime = getUsedTime((testEndTime.value - testStartTime.value) / 1000)
    recordFrom.value.correctNum = correctNum.value
    recordFrom.value.correctRate = correctNum.value / total.value
    // console.log(recordFrom.value)
    handleInsertRecordData(recordFrom.value)
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  data.type = 'senior'
  addStudy_record(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      correctNum.value = 0
      practiceId.value = Math.random().toString().substring(2)
      proxy.$modal.msgSuccess("提交成功")
    }
  })
}

function searchByUnit() {
  correctNum.value = 0
  resetTimer()
  proxy.$modal.msg("查询的组号:" + groupNum.value)
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectedData.value = []
  multiple.value = !selection.length
  selection.map(item => {
    selectedData.value.push(item)
  })
  selectedDataTemp.value = JSON.parse(JSON.stringify(selectedData.value))
}

function hiddenEng() {
  if (multipleEng.value) {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index => index._id === item._id);
      let number = pageData.value.indexOf(find);
      rowRecordMap.value.set(item.index, item);
      pageData.value[number].name = ''
      pageData.value[number].statusEng = true
    })
  } else {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index =>
          index._id === item._id
      );
      let number = pageData.value.indexOf(find);
      pageData.value[number].name = item.name
      pageData.value[number].statusEng = false
    })
  }
  multipleEng.value = !multipleEng.value
}

function hiddenChn() {
  if (multipleChn.value) {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index =>
          index._id === item._id
      );
      let number = pageData.value.indexOf(find);
      rowRecordMap.value.set(item.index, item);
      pageData.value[number].chinese = ''
      pageData.value[number].statusChn = true
    })
  } else {
    selectedDataTemp.value.forEach(item => {
      let find = pageData.value.find(index =>
          index._id === item._id
      );
      let number = pageData.value.indexOf(find);
      pageData.value[number].chinese = item.chinese
      pageData.value[number].statusChn = false
    })
  }
  multipleChn.value = !multipleChn.value
}

const indexMethod = (index) => {
  return index
}

function hiddenColumn1(row) {
  // rowRecord.value = Object.assign({}, row);
  // rowRecord.value = deepClone(row)
  row.statusEng = !row.statusEng
  if (row.statusEng) {
    // rowRecord.value = JSON.parse(JSON.stringify(row))   //对象深拷贝-待用
    if (!rowRecordMap.value.has(row.index)) {
      rowRecordMap.value.set(row.index, JSON.parse(JSON.stringify(row)))
    }
    row.name = ''
  } else {
    row.name = rowRecordMap.value.get(row.index)['name']
  }
}

function hiddenColumn2(row) {
  row.statusChn = !row.statusChn
  if (row.statusChn) {
    if (!rowRecordMap.value.has(row.index)) {
      rowRecordMap.value.set(row.index, JSON.parse(JSON.stringify(row)))
    }
    row.chinese = ''
  } else {
    row.chinese = rowRecordMap.value.get(row.index)['chinese']
  }
}

function resetQuery() {
  pageData.value = shuffleArray(pageData.value)
}

function handleColumnAudio(row, rate) {
  if (rate === undefined || rate === null) {
    rate = 0.7
  }
  row.voiceCount ++
  window.speechSynthesis.resume();
  const speech = new SpeechSynthesisUtterance();
  speech.text = row.name;
  speech.lang = "en-US";
  speech.volume = 1;
  speech.rate = rate;
  speech.pitch = 1;
  window.speechSynthesis.speak(speech);
}

</script>

<style scoped lang="scss">
.header {
  display: flex;
  margin-top: 20px;
  margin-left: 20px;
  flex-wrap: wrap;
}

.wordSentence {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* 关键：垂直排列 */
  gap: 10px; /* 项目间距 */
}

//.center-input {
//  :deep(.el-input__inner) {
//    text-align: center;
//  }
//}

/* 左下角 */
:deep(.el-backtop) {
  right: auto !important;
  left: 210px;
  bottom: 20px;
}

/* 确保 input 不换行 */
:deep(.el-form-item__content) {
  display: inline-block;
}

/* 确保 input 不换行 */
:deep(.el-form-item__content) {
  display: inline-block;
}

.el-form--inline .el-form-item {
  margin-right: 10px;
}

/* 自定义大小的回到顶部按钮 */
:deep(.custom-backtop) {
  /* 自定义大小 */
  width: 80px;
  height: 40px;

  /* 其他样式调整 */
  line-height: 60px;
  border-radius: 8px;
  background-color: #67c23a;
  color: white;
  text-align: center;
  font-size: 22px;

  /* 悬停效果 */
  transition: all 0.3s;
}

.time-display {
  font-size: 1.0rem;
  font-weight: bold;
  color: #323233;
  margin: 0 10px 0 20px;
  padding: 0 10px 0 20px;
  border: none;
  border-radius: 12px;
  background-color: #ffffff;
  min-width: 120px;
  letter-spacing: 3px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

</style>
